import React, { Component } from "react";
import { connect } from "dva";
import LzEditor from "react-lz-editor";
import {
  Input,
  Button,
  DatePicker,
  TreeSelect,
  Table,
  Select,
  Modal,
  message
} from "antd";
import moment from "moment";
import { withRouter } from "dva/router";

import { gup } from "../../../utils/utils";
import * as ajax from "../../../services/api";
import MessageDetail from "./messageDetail";

const { confirm } = Modal;
const { Option } = Select;
const { RangePicker } = DatePicker;
const dateFormat = "YYYY-MM-DD";

@connect(state => ({
  global: state.global,
  currentUser: state.user.currentUser,
  fetchingNotices: state.global.fetchingNotices
}))
@withRouter
export default class ReceiveList extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      treeData: [],
      // visibleuser:false,
      selectedRowIds: [], //需要删除的信息id值集合1
      listPage: [], //表格数据
      selectedRowKeys: [],
      // selectUserIdArrays:[], //选中的id集合，保存用的
      userIdArrays: [], //表单显示用的人员id集合
      responseList: [],
      dataSource: {
        briefIntroduce: "" //富文本
      },
      messageModal: false, //发送消息弹窗
      checkModal: false, //查看消息弹窗
      titleLength: "0", //发送消息弹窗  标题的长度
      record: {},
      input_val: "", //关键字输入框
      startDate: "",
      endDate: "",
      input_wed: "", //发送信息的标题输入框
      isRead: "" //已读未读
    };

    console.log(gup("id"));
  }

  componentDidMount() {
    this.search();

    //获取部门树数据
    ajax.getTreeperBydepart({}).then(data => {
      this.setState({ treeData: data.data });
      console.log("部门信息", data.data);
    });
  }

  //时间选择
  onChangeTime = (date, dateString) => {
    console.log("2323232", dateString[0]);
    console.log("34343434", dateString[1]);
    this.setState({
      startDate: dateString[0],
      endDate: dateString[1]
    });
  };

  //已读，未读
  handleChangeIsRead = value => {
    console.log(`selected ${value}`);
    this.setState({ isRead: value });
  };

  // 富文本
  receiveHtml = content => {
    this.setState({
      dataSource: {
        briefIntroduce: content //富文本
      }
    });
  };

  //输入框的书写
  inputTracknameChange = e => {
    // let tmp = Object.assign({}, this.state.ajaxPagePara);
    // tmp.data.Trackname = e.target.value.trim();
    console.log(e.target.value.trim());
    this.setState({
      input_val: e.target.value.trim()
    });
  };

  //分页消息列表（收件人方）
  search = () => {
    ajax
      .messageReceiveList({
        pageNumber: 1,
        pageSize: 50,
        startDate: this.state.startDate,
        endDate: this.state.endDate,
        key: this.state.input_val,
        isRead: this.state.isRead
      })
      .then(
        data => {
          console.log("wewewe", data);
          this.setState({
            listPage: data.data.data
          });
        },
        err => {
          console.log("err", err);
        }
      );
  };

  //重置
  resetQueryCond = () => {
    this.setState(
      {
        startDate: "",
        endDate: "",
        input_val: "",
        isRead: ""
      },
      () => {
        this.search();
      }
    );
  };

  // 订单删除
  orderDelete = orderID => {
    ajax.messageDeleteSelectMessage({ ids: orderID.join(",") }).then(
      data => {
        console.log("消息删除", data);
        this.setState({
          selectedRowIds: [],
          selectedRowKeys: []
        });
        this.search();
      },
      err => {
        console.log("消息删除失败", err);
        message.warning("消息删除失败！" + err);
      }
    );
  };

  showDeleteConfirm = record => {
    confirm({
      title: "是否删除所选信息，删除后无法找回。是否确认删除？",
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        this.orderDeleteXiao(record.id);
      },
      onCancel() {
        console.log("Cancel");
      }
    });
  };

  orderDeleteXiao = orderID => {
    ajax.messageDeleteMessageById({ ids: orderID }).then(
      data => {
        console.log("消息删除", data);
        this.search();
      },
      err => {
        console.log("消息删除失败", err);
        message.warning("消息删除失败！" + err);
      }
    );
  };

  // 批量删除
  handleDeleteList = () => {
    const that = this;
    const keyNumber = this.state.selectedRowIds.length;
    const keyId = this.state.selectedRowKeys;
    console.log("id集合" + keyId);
    if (keyNumber <= 0) {
      message.warning("请选择需要删除的信息！");
    } else {
      confirm({
        title: "是否删除所选方案，删除后方案不可找回。是否确认删除？",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          that.orderDelete(keyId);
        },
        onCancel() {
          console.log("Cancel");
        }
      });
    }
  };

  // 批量设置已读
  handleRead = () => {
    const keyNumber = this.state.selectedRowIds.length;
    const keyId = this.state.selectedRowKeys;
    if (keyNumber <= 0) {
      message.warning("请选择需要设为已读的信息！");
    } else {
      ajax
        .updateSelectMessageRead({
          ids: keyId.join(",")
        })
        .then(
          data => {
            console.log("设置为已读", data);
            this.setState({
              selectedRowIds: [],
              selectedRowKeys: []
            });
            this.search();
          },
          err => {
            console.log("设置为已读失败", err);
            message.warning("设置为已读失败！" + err);
          }
        );
    }
  };

  // 发送消息
  sendMessage = () => {
    this.setState({
      messageModal: true
    });
  };

  //发送消息
  handleMessageOk = () => {
    console.log("标题名字", this.state.input_wed);
    console.log("内容", this.state.dataSource.briefIntroduce);
    if (this.state.userIdArrays.length === 0) {
      message.warning("请选择人员");
      return;
    }
    if (this.state.input_wed.trim() === "") {
      //只限制长度
      message.warning("标题不能为空");
      return;
    }
    if (this.state.dataSource.briefIntroduce.trim().length < 20) {
      message.warning("内容不能小于20");
      return;
    }

    // console.log("过滤>>>>>>>>>>>>>>>>>",filterUserIdArrays);
    ajax
      .messageSaveMessageCommon({
        title: this.state.input_wed,
        content: this.state.dataSource.briefIntroduce,
        ids: this.state.userIdArrays.join(",")
      })
      .then(() => {
        // console.log(data, '成功啦成功啦');
        // message.success('发送成功');//全局统一处理，这里不再处理
        this.renderOrderList();
        this.search();
        this.props.dispatch({
          type: "global/fetchNotices"
        });
      });

    this.setState({
      messageModal: false,
      userIdArrays: "",
      input_wed: "", //发送信息的标题输入框
      dataSource: {
        briefIntroduce: "" //富文本
      }
    });
  };

  //弹窗关闭按钮
  handleMessageCancel = () => {
    this.setState({
      messageModal: false
    });
  };

  // 发送消息弹窗
  inputMessageName = e => {
    const messageLength = e.target.value.length;
    this.setState({
      titleLength: messageLength,
      input_wed: e.target.value
    });
  };

  // 表格渲染
  renderOrderList = () => {
    const pageInitStudent = {
      defaultPageSize: 10,
      showQuickJumper: true,
      pageSizeOptions: ["5", "10", "15", "20", "25"],
      showSizeChanger: true
    };

    const selectedRowKey = this.state.selectedRowKeys;
    const rowSelection = {
      selectedRowKeys: selectedRowKey,

      onChange: selectedRowKeys => {
        console.log("selectedRowKeys", selectedRowKeys);

        this.setState({
          selectedRowKeys
        });
      },
      onSelect: (record, selected, selectedRows) => {
        const selectId = this.state.selectedRowIds;
        if (selected === true) {
          selectId.push(record.perNewsRelaId);
        } else {
          for (let i = 0; i < selectId.length; i++) {
            if (selectId[i] === record.perNewsRelaId) {
              selectId.splice(i, 1);
              break;
            }
          }
        }
        this.setState({
          selectedRowIds: selectId
        });
        console.log(
          `record:`,
          record.perNewsRelaId,
          `selected:`,
          selected,
          `selectedRows:`,
          selectedRows
        );
      },
      onSelectAll: (selected, selectedRows) => {
        let selectId = [];
        if (selected === true) {
          for (let i = 0; i < selectedRows.length; i++) {
            selectId.push(selectedRows[i].perNewsRelaId);
          }
        } else {
          selectId = [];
          // selectedRowKeys:selectedRowKey
        }
        this.setState({
          selectedRowIds: selectId
        });
      }
    };

    const columns = [
      {
        title: "发件人",
        dataIndex: "addresser",
        key: "addresser",
        render: (text, record) => (
          <span>
            {record.isRead === "1" ? (
              <span style={{ color: "#999" }}>{record.addresser}</span>
            ) : (
              <span style={{ color: "#666" }}>{record.addresser}</span>
            )}
          </span>
        )
      },
      {
        title: "标题",
        dataIndex: "title",
        key: "title",
        render: (text, record) => (
          <span>
            {record.isRead === "1" ? (
              <span
                style={{
                  color: "#999",
                  display: "inline-block",
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  width: "300px"
                }}
              >
                {record.title}
              </span>
            ) : (
              <span
                style={{
                  color: "#666",
                  display: "inline-block",
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  width: "300px"
                }}
              >
                {record.title}
              </span>
            )}
          </span>
        ),
        width: 380
      },
      {
        title: "时间",
        dataIndex: "sendTime",
        key: "sendTime"
      },
      {
        title: "状态",
        dataIndex: "isRead",
        key: "isRead",
        render: (text, record) => (
          <span>
            {record.isRead === "1" ? (
              <span
                style={{
                  color: "#999",
                  display: "inline-block",
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  width: "300px"
                }}
              >
                已读
              </span>
            ) : (
              <span
                style={{
                  color: "#666",
                  display: "inline-block",
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  width: "300px"
                }}
              >
                未读
              </span>
            )}
          </span>
        )
      },
      {
        title: "操作",
        render: (text, record) => (
          <div>
            <span
              style={{
                color: "#108EE9",
                cursor: "pointer",
                marginRight: "20px"
              }}
              onClick={() => {
                this.setState({ record, checkModal: true });
              }}
            >
              查看
            </span>
            <span
              style={{ color: "#108EE9", cursor: "pointer" }}
              onClick={this.showDeleteConfirm.bind(this, record)}
            >
              删除
            </span>
          </div>
        )
      }
    ];

    const tmp = this.state.listPage.map(val => {
      const param = val;
      param.key = val.id;
      return param;
    });

    return (
      <Table
        dataSource={tmp}
        columns={columns}
        rowSelection={rowSelection}
        pagination={pageInitStudent}
      />
    );
  };

  //树选中事件
  treeSelectOnChangeHandler = value => {
    this.setState({ userIdArrays: value });
  };

  render() {
    console.log(this.props.location, "this.props.location");
    const stateDataSource = this.state.dataSource;
    const uploadProps = {
      action: ajax.uploadUrl,
      accept: "image/*",
      onChange: info => {
        console.log(info.fileList, "onChange");
        let responseList = info.fileList;
        responseList = responseList.slice(-2);

        responseList = responseList.map(file => {
          if (file.response) {
            file.url = `${file.response.data}&t=10`;
            console.log(file.response.data, "file.response.data");
          }
          console.log(file, "file");
          return file;
        });
        console.log(responseList, "responseList2");

        responseList = responseList.filter(file => {
          if (file.response) {
            return file.response.retType === "0";
          }
          return true;
        });

        console.log(responseList, "responseList3");

        this.setState({ responseList });
      },
      listType: "picture",
      fileList: this.state.responseList,
      name: "xfile",
      data: file => {
        console.log(file);
      },
      multiple: true,
      beforeUpload: this.beforeUpload,
      showUploadList: true
    };

    const tProps = {
      treeData: this.state.treeData,
      value: this.state.userIdArrays,
      onChange: this.treeSelectOnChangeHandler,
      treeCheckable: true,
      // labelInValue:true,
      allowClear: true,
      treeNodeFilterProp: "label",
      showCheckedStrategy: TreeSelect.SHOW_CHILD,
      searchPlaceholder: "请选择",
      style: {
        width: 560,
        background: "#f5f5f5"
      }
    };
    return (
      <div className="message-receive">
        <div className="form">
          <label>
            关键字：
            <Input
              style={{ width: 214 }}
              placeholder="请输入发件人/标题"
              onChange={this.inputTracknameChange}
              value={this.state.input_val}
              maxLength="20"
            />
          </label>
          <label style={{ marginLeft: 16 }}>
            接收时间：
            <RangePicker
              format={dateFormat}
              onChange={this.onChangeTime}
              value={[
                this.state.startDate === ""
                  ? null
                  : moment(this.state.startDate, dateFormat),
                this.state.endDate === ""
                  ? null
                  : moment(this.state.endDate, dateFormat)
              ]}
            />
          </label>
          <label style={{ marginLeft: 16 }}>
            是否已读：
            <Select
              style={{ width: 120 }}
              value={this.state.isRead}
              onChange={this.handleChangeIsRead}
              placeholder="请选择"
            >
              <Option value="">全部</Option>
              <Option value="1">已读</Option>
              <Option value="0">未读</Option>
            </Select>
          </label>
          <Button
            style={{ marginLeft: 16 }}
            type="primary"
            onClick={this.search}
          >
            搜索
          </Button>
          <Button style={{ marginLeft: 16 }} onClick={this.resetQueryCond}>
            重置
          </Button>
        </div>
        <div className="receive-list">
          <div className="receive-row">
            <Button type="primary" onClick={this.sendMessage}>
              发送信息
            </Button>
            {/*发送信息弹窗*/}
            <Modal
              width={700}
              title="发送信息"
              maskClosable={false}
              visible={this.state.messageModal}
              onOk={this.handleMessageOk}
              onCancel={this.handleMessageCancel}
            >
              <div>
                <label
                  style={{
                    display: "inline-block",
                    width: "80px",
                    textAlign: "right"
                  }}
                >
                  收件人：
                </label>
                <TreeSelect {...tProps} />
              </div>
              <div style={{ position: "relative" }}>
                <label
                  style={{
                    display: "inline-block",
                    width: "80px",
                    textAlign: "right",
                    marginTop: "26px"
                  }}
                >
                  标题：
                </label>
                <Input
                  style={{ width: 560, paddingRight: "60px" }}
                  placeholder="请输入"
                  maxLength="20"
                  onChange={this.inputMessageName}
                  value={this.state.input_wed}
                />
                <span
                  style={{
                    position: "absolute",
                    top: "28px",
                    right: "20px",
                    color: "#999",
                    fontSize: "12px"
                  }}
                >
                  {this.state.titleLength}/20
                </span>
              </div>
              <div className="clearfix">
                <label
                  style={{
                    display: "inline-block",
                    width: "80px",
                    textAlign: "right",
                    marginTop: "26px",
                    float: "left"
                  }}
                >
                  内容：
                </label>
                <div className="Rich-text">
                  <LzEditor
                    uploadProps={uploadProps}
                    autoSave={false}
                    video={false}
                    audio={false}
                    cbReceiver={this.receiveHtml}
                    importContent={stateDataSource.briefIntroduce}
                    key="LzEditor"
                    // convertFormat="raw"
                  />
                </div>
              </div>
            </Modal>
            <Button onClick={this.handleRead}>批量设置为已读</Button>
            <Button type="danger" ghost onClick={this.handleDeleteList}>
              批量删除
            </Button>
          </div>
        </div>
        {this.renderOrderList()}
        {/*查看信息弹窗1*/}
        <MessageDetail
          record={this.state.record}
          visible={this.state.checkModal}
          closeModal={() => {
            this.setState({ checkModal: false });
          }}
        />
      </div>
    );
  }
}
